package com.inventive.jmscache.server;

import org.junit.Assert;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.jms.*;

/**
 * @author Grant Little <grant.little@coreservices.com.au>
 */
public class JmsCacheQueueConsumer {

    private JmsCacheQueue destination;
    private QueueConnectionFactory connectionFactory;
    private QueueConnection connection;
    private QueueSession session;
    private MessageConsumer consumer;
    private JmsCacheServer jmsCacheServer;
    private MessageListener messageListener;

    public JmsCacheQueueConsumer(String destinationName, MessageListener messageListener) {
        this.messageListener = messageListener;
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        jmsCacheServer = applicationContext.getBean(JmsCacheServer.class);
        try {
            connectionFactory = applicationContext.getBean(JmsCacheQueueConnectionFactory.class);
            destination = new JmsCacheQueue(jmsCacheServer, destinationName);
            connection = connectionFactory.createQueueConnection();
            session = connection.createQueueSession(true, AcknowledgeMode.SESSION_TRANSACTED.ordinal());
            consumer = session.createConsumer(destination);
        } catch (JMSException e) {
            Assert.fail();
        }
    }

    public void start() {
        try {
            consumer.setMessageListener(messageListener);
        } catch (JMSException e) {
            Assert.fail();
        }
    }
}